package com.mall.user.services;/**
 * Created by ciggar on 2019/7/30.
 */

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.LoginDto;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.yetus.audience.InterfaceAudience;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/7/30-下午11:51
 */
@Slf4j
@Component
@Service
public class MemberServiceImpl implements IMemberService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    JavaMailSender mailSender;

//    @Autowired
//    IUserLoginService userLoginService;

    @Autowired
    MemberConverter memberConverter;

    /**
     * 根据用户id查询用户会员信息
     * @param request
     * @return
     */
    @Override
    public QueryMemberResponse queryMemberById(QueryMemberRequest request) {
        QueryMemberResponse queryMemberResponse=new QueryMemberResponse();
        try{
            request.requestCheck();
            Member member=memberMapper.selectByPrimaryKey(request.getUserId());
            if(member==null){
                queryMemberResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                queryMemberResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            }
            queryMemberResponse=memberConverter.member2Res(member);
            queryMemberResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            queryMemberResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("MemberServiceImpl.queryMemberById Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(queryMemberResponse,e);
        }
        return queryMemberResponse;
    }

    @Override
    public HeadImageResponse updateHeadImage(HeadImageRequest request) {
        HeadImageResponse response=new HeadImageResponse();
        //TODO
        return response;
    }

    @Override
    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
        return null;
    }

//    @Override
//    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
//        UpdateMemberResponse response = new UpdateMemberResponse();
//        try{
//            request.requestCheck();
//            CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
//            checkAuthRequest.setToken(request.getToken());
//            CheckAuthResponse authResponse = userLoginService.validToken(checkAuthRequest);
//            if (!authResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
//                response.setCode(authResponse.getCode());
//                response.setMsg(authResponse.getMsg());
//                return response;
//            }
//            Member member = memberConverter.updateReq2Member(request);
//            int row = memberMapper.updateByPrimaryKeySelective(member);
//            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//            log.info("MemberServiceImpl.updateMember effect row :"+row);
//        }catch (Exception e){
//            log.error("MemberServiceImpl.updateMember Occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
//        }
//        return response;
//    }


    /**
     * create by zhw
     * 用户注册
     * @param request
     * @return
     */
    @Override
    public ResponseData addMember(UserRegisterRequest request) {
        //先查该用户是否存在
        String email = request.getEmail();
        String userName = request.getUserName();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",userName).andEqualTo("email",email);
        int count = memberMapper.selectCountByExample(example);

        if (count != 0){
            //该用户已存在
            return new ResponseUtil<String>().setErrorMsg("该用户已注册");
        }
        else {
            //注册新用户，写入数据库
            Member member = new Member();
            member.setEmail(email);
            member.setPassword(request.getUserPwd());
            member.setUsername(userName);
            Date date = new Date(System.currentTimeMillis());
            member.setUpdated(date);
            member.setCreated(date);
            member.setIsVerified("N");
            //TODO member 里面有个state字段不知道是什么意思
//            member.setState(1);
            memberMapper.insertSelective(member);


            String uuid = UUID.randomUUID().toString();
            // 3.发送用户激活邮件
            new Thread(){
                @Override
                public void run(){
                    sendEmail(uuid,request);
                    super.run();
                }
            }.start();

            return new ResponseUtil<String>().setData("success");
        }

    }

    private void sendEmail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("CSMALL用户激活");
        simpleMailMessage.setFrom("18722434816@163.com");
        simpleMailMessage.setTo(request.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8080/user/verify?uid=").append(uuid)
                .append("&username=").append(request.getUserName());
        simpleMailMessage.setText(stringBuilder.toString());
        mailSender.send(simpleMailMessage);

    }

    /**
     * 用户登录
     * create by zhw
     * @param userLoginRequest
     * @return
     */
    @Override
    public UserLoginResponse queryMemberByUserNameAndPassword(UserLoginRequest userLoginRequest) {
        String password = userLoginRequest.getPassword();
        String userName = userLoginRequest.getUserName();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("password", password).andEqualTo("username", userName);

        //查询
        Member member = memberMapper.selectOneByExample(example);
        if (member == null){
            //用户不存在
            return null;
        }
        else {
            //验证成功


            //token
            String token = JwtTokenUtils.builder().msg(member.getId().toString()).build().creatJwtToken();

            UserLoginResponse userLoginResponse = new UserLoginResponse();
            userLoginResponse.setId(member.getId());
            userLoginResponse.setUsername(member.getUsername());
            userLoginResponse.setPhone(member.getPhone());
            userLoginResponse.setEmail(member.getEmail());
            userLoginResponse.setSex(member.getSex());
            userLoginResponse.setAddress(member.getAddress());
            userLoginResponse.setFile(member.getFile());
            userLoginResponse.setDescription(member.getDescription());
            userLoginResponse.setPoints(member.getPoints());
            userLoginResponse.setBalance(member.getBalance());
            userLoginResponse.setState(member.getState());
            userLoginResponse.setToken(token);


            return userLoginResponse ;

        }

    }

    /**
     * 验证登录
     * @param token
     * @return
     */
    @Override
    public ResponseData queryMemberByToken(String token) {
        String s = JwtTokenUtils.builder().token(token).build().freeJwt();
        Long userId = Long.parseLong(s);
        Member member = memberMapper.selectByPrimaryKey(userId);
        LoginDto loginDto = new LoginDto();
        loginDto.setUid(member.getId());
        loginDto.setUsername(member.getUsername());

        return new ResponseUtil<LoginDto>().setData(loginDto,"success");
    }

    @Override
    public ResponseData userVerify(String username) {

        Member member = new Member();
        member.setIsVerified("Y");
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",username);
        memberMapper.updateByExampleSelective(member,example);

        return new ResponseUtil<>().setData("激活成功，可以登录了");
    }

    @Override
    public boolean isVerify(String userName) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",userName);
        List<Member> members = memberMapper.selectByExample(example);
        Member member = members.get(0);
        String isVerified = member.getIsVerified();
        return isVerified.equals("Y");
    }

}
